package com.sp.scmdb.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sp.scmdb.bean.EmployeeBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.common.action.BaseAction;
import com.sp.scmdb.entity.Department;
import com.sp.scmdb.entity.Duty;
import com.sp.scmdb.entity.Employee;
import com.sp.scmdb.entity.RelEmpArea;
import com.sp.scmdb.entity.Shifts;
import com.sp.scmdb.entity.Tag;
import com.sp.scmdb.entity.Title;
import com.sp.scmdb.entity.WorkTime;
import com.sp.scmdb.entity.WorkType;
import com.sp.scmdb.exception.ExcelException;
import com.sp.scmdb.service.EmployeeService;
import com.sp.scmdb.service.ExportExcelService;
import com.sp.scmdb.utils.EmpCollectionGroup;

@Controller("employeeAction")
@Scope("prototype")
public class EmployeeAction extends BaseAction<EmployeeBean> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(EmployeeAction.class);
	private EmployeeService empService;
	private ExportExcelService exportExcelService;
	private InputStream excelStream;
	private String fileName;
	private File attachment;
	private String attachmentFileName;
	private String attachmentContentType;
	private InputStream imagStream;
	private String result; 

	@SuppressWarnings("unchecked")
	public String findAll() {

		UserBean user = (UserBean) session.get("user");
		try {
			EmployeeBean empBean = null;
			if (StringUtils.isNotEmpty(pageName)) {
				empBean = (EmployeeBean) session.get("empBean");
			}else{
				entity.setPageNo(1);
			}
			entity = empService.queryAll(entity, empBean, user);
			// 
			session.put("empBean", entity);
			session.put("empTypeList", CommonParamter.TypeCommon.getEmpType()); //是否特种人员列表
			session.put("sexType", CommonParamter.TypeCommon.getSexType());
			session.put("yesNO", CommonParamter.TypeCommon.getYesNo());
			
			this.button("",
					"Super.editData('/SCMDB/employeeAction!findEmp.action?id=',700,500)",
					"");
		} catch (Exception e) {
			return "login";
		}

		return SUCCESS;
	}
	
	public String findEmployeeList() {
		String hql = "";
		if(StringUtils.isNotEmpty(entity.getEmpLabelID())) {
			hql += " and e.empLableID = " + entity.getEmpLabelID();
		}
		if(StringUtils.isNotEmpty(entity.getEmpName())) {
			hql += " and e.empName like '%" + entity.getEmpName() + "%' ";
		}
		List<EmployeeBean> employeeList = empService.getEmployeeList(hql);
		entity.setAllList(employeeList);
		entity.setList(employeeList.subList(entity.getCurrentRow(), entity.getLastRow()));
		return "employeeList";
	}

	public String newEmp() {
		UserBean user = (UserBean) session.get("user");

		entity.setListDepartment(empService.getListDepartment(user));
		entity.setListDuty(empService.getListDuty());
		entity.setListTitle(empService.getListTitle());
		entity.setListWorkTime(empService.getListWorkTime());
		entity.setListMaxWorkTime(empService.getListMaxWorkTime());
		entity.setListArea(empService.getListArea());
		entity.setListShifts(empService.getListShifts());
		entity.setListWorkType(empService.getListWorkType());
		entity.setListRestrictAlarm(empService.getRestrictAlarm());
		
		return "newSucc";
	}

	public String addEmp() {
		try {
			UserBean user = (UserBean) session.get("user");
			String result = empService.newEmp(entity, user);
			if ("10".equals(result)) {
				messageSession("0", "卡号" + entity.getEmpLabelID() + "重复！");

			} else if ("20".equals(result)) {
				messageSession("0", "卡号" + entity.getEmpLabelID() + "不存在或已使用！");

			} else if ("30".equals(result)) {
				messageSession("0", "编号" + entity.getEmpLabelID() + "重复！");

			} else {
				messageSession(result, "卡号");
			}

		} catch (RuntimeException e) {
			log.error("addDep fail!reason:" + e.getMessage());
			return "fail";
		} catch (Exception e) {
			log.error("addDep fail!reason:" + e.getMessage());
			return "error";
		}
		return "commitSucc";
	}

	public String delEmp() {
		try {
			UserBean user = (UserBean) session.get("user");
			String empID = request.getParameter("id");
			if (StringUtils.isNotEmpty(empID)) {
				String[] arr = empID.split(",");
				String result = empService.delEmp(arr, user);
				if ("1".equals(result)) {
					messageSession(result, "卡号");
				} else {
					messageSession("0", result);
				}
			}
			if (log.isInfoEnabled()) {
				log.info("edit suncce");
			}
		} catch (Exception e) {
			log.error("add fail");
			return "fail";
		}
		return "commitSucc";
	}

	public String findEmp() {
		UserBean user = (UserBean) session.get("user");

		entity.setListDepartment(empService.getListDepartment(user));
		entity.setListDuty(empService.getListDuty());
		entity.setListTitle(empService.getListTitle());
		entity.setListWorkTime(empService.getListWorkTime());
		entity.setListMaxWorkTime(empService.getListMaxWorkTime());
		entity.setListArea(empService.getListArea());
		entity.setListShifts(empService.getListShifts());
		entity.setListWorkType(empService.getListWorkType());
		entity.setListRestrictAlarm(empService.getRestrictAlarm());
		entity.setListBuMen(empService.getListBuMen());
		try {
			String empId = request.getParameter("id");
			Employee emp = empService.getById(empId);
			if (emp == null) {
				request.setAttribute("message", "人员不存在！");
			} else {
				entity.setId(empId);
				entity.setEmpLabelID(emp.getEmpLableID());
				entity.setEmpName(emp.getEmpName());
				entity.setEmpWorkID(emp.getEmpWorkID());
				entity.setEmpAddr(emp.getEmpAddr());
				entity.setEmpDepID(emp.getEmpDepID());
				entity.setEmpDutyID(emp.getEmpDutyID());
				entity.setEmpPhone(emp.getEmpPhone());
				entity.setIdentityNo(emp.getIdentityNo());
				entity.setEmpSex(emp.getEmpSex());
				if (emp.getEmpPhoto() != null) {
					entity.setEmpPhotoFileName("");
				}
				entity.setEmpWorkTime(emp.getEmpWorkTime());
				entity.setEmpMaxWorkTime(emp.getEmpMaxWorkTime());
				entity.setEmpType(emp.getEmpType());
				entity.setEmpShiftsID(emp.getEmpShiftID());
				entity.setEmpWorkTypeID(emp.getEmpWorkTypeID());
				entity.setEmpTitleID(emp.getEmpTitleID());
				entity.setReID(emp.getReID());
				entity.setEmpBuMenID(emp.getEmpBuMenID());
				entity.setBlood(emp.getBlood());
				entity.setProName(emp.getProName());
				entity.setProID(emp.getProID());
				entity.setPeccancys(emp.getPeccancys());
				entity.setUnitName(emp.getUnitName());
				entity.setEntryTime(emp.getEntryTime());
				entity.setSpection(emp.getSpection());
				entity.setContract(emp.getContract());
				entity.setSafetys(emp.getSafetys());
				entity.setContractTime(emp.getContractTime());
				entity.setCertificate(emp.getCertificate());
				entity.setCertificateName(emp.getCertificateName());
				entity.setTownSecure(emp.getTownSecure());
				entity.setOtherSecure(emp.getOtherSecure());
				entity.setSafeCard(emp.getSafeCard());
				entity.setCardTime(emp.getCardTime());
				entity.setSafePosts(emp.getSafePosts());
				entity.setPostsTime(emp.getPostsTime());
				entity.setTrack(emp.getTrack());
				entity.setTrackTime(emp.getTrackTime());
				entity.setSafeOption(emp.getSafeOption());
				entity.setSafeOptionTime(emp.getSafeOptionTime());
				entity.setOrderBook(emp.getOrderBook());
				entity.setOrderTime(emp.getOrderTime());
				// 如果是特种人员，则获取其经过的区域及时间
				RelEmpArea relEmpArea = null;
				List<RelEmpArea> listRelEmpAre = new ArrayList<RelEmpArea>();
				Iterator<RelEmpArea> iterator = emp.getRelEmpAreaList().iterator();
				while (iterator.hasNext()) {
					relEmpArea = iterator.next();
					listRelEmpAre.add(relEmpArea);
				}
				entity.setListRelEmpAre(listRelEmpAre);

			}
		} catch (Exception e) {
			log.error("add fail");
			return "login";
		}
		return "editSucc";
	}
	
	public String getImag(){
		String empId = request.getParameter("id");
		Employee emp = empService.getById(empId);
		if (emp == null) {
			request.setAttribute("message", "人员不存在！");
		} else {			
			try {
				imagStream = new ByteArrayInputStream(emp.getEmpPhoto());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "imag";
	}

	public String editEmp() {
		try {
			UserBean user = (UserBean) session.get("user");
			String result = empService.editEmp(entity, user);

			if ("10".equals(result)) {
				messageSession("0", "卡号" + entity.getEmpLabelID() + "重复！");

			} else if ("20".equals(result)) {
				messageSession("0", "卡号" + entity.getEmpLabelID() + "不存在或已使用！");

			} else if ("30".equals(result)) {
				messageSession("0", "编号" + entity.getEmpWorkID() + "重复！");

			} else {
				messageSession(result, "卡号");
			}

		} catch (Exception e) {
			log.error("edit fail");
			return "fail";
		}
		return "commitSucc";
	}

	public String downLoadExcel() {
		try {
			Workbook wb = new HSSFWorkbook();
			String tableName = "人员信息模板";
			wb = exportExcelService.createEmployeeExcel(tableName);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			tableName = new String("人员信息模板".getBytes(), "ISO-8859-1");
			this.fileName = tableName + ".xls";
			wb.write(out);
			excelStream = new ByteArrayInputStream(out.toByteArray());
			out.flush();
			out.close();
			return "outExcel";
		} catch (ExcelException excel) {
			log.error("create excel failed! reason:" + excel.getMessage());
			return "fail";
		} catch (Exception e) {
			log.error("excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	@SuppressWarnings("unchecked")
	public String importExcel() {
		UserBean user = (UserBean) session.get("user");
		EmpCollectionGroup empGroup = new EmpCollectionGroup();
		List<Department> depList = empService.getListDepartment(user);
		empGroup.groupDep(depList);
		List<Duty> dutyList = empService.getListDuty();
		empGroup.groupDuty(dutyList);
		List<Title> titleList = empService.getListTitle();
		empGroup.groupTitle(titleList);
		List<WorkTime> workTimeList = empService.getListWorkTime();
		empGroup.groupWorkTime(workTimeList);
		List<WorkTime> maxWorkTimeList = empService.getListMaxWorkTime();
		empGroup.groupMaxWorkTime(maxWorkTimeList);
		List<Shifts> shiftsList = empService.getListShifts();
		empGroup.groupShifts(shiftsList);
		List<WorkType> workTypeList = empService.getListWorkType();
		empGroup.groupWorkType(workTypeList);
		session.put("empGroup", empGroup);
		return "importExcel";
	}

	public String commitImportExcel() {
		String result = CommonParamter.CHECK_SUCCESS;
		UserBean user = (UserBean) session.get("user");
		try {
			EmpCollectionGroup empGroup = (EmpCollectionGroup) session.get("empGroup");
			if (attachmentFileName.toLowerCase().endsWith("xls")) {
				String errorInfo = exportExcelService.importExcel(attachment, attachmentFileName, empGroup, user);
				if (StringUtils.isNotEmpty(errorInfo)) {
					messageSession("0", errorInfo);
				} else {
					messageSession(result, "导入人员信息");
				}
			} else {
				messageSession("0", "请输入后缀为xls的EXCEL文件路径！");
			}
			return "commitSucc";
		} catch (Exception e) {
			log.error("import excel failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	
	public String getTags(){
		String tagNo = request.getParameter("tagNo");
		List<Tag> listTag = empService.getUnusedTags(tagNo);
		
		// 将entity转换成json
		JSONArray jo = JSONArray.fromObject(listTag);
		result = jo.toString();
		
		return SUCCESS;
	}

	public InputStream getImagStream() {
		return imagStream;
	}

	public void setImagStream(InputStream imagStream) {
		this.imagStream = imagStream;
	}

	public File getAttachment() {
		return attachment;
	}

	public void setAttachment(File attachment) {
		this.attachment = attachment;
	}

	public String getAttachmentFileName() {
		return attachmentFileName;
	}

	public void setAttachmentFileName(String attachmentFileName) {
		this.attachmentFileName = attachmentFileName;
	}

	public String getAttachmentContentType() {
		return attachmentContentType;
	}

	public void setAttachmentContentType(String attachmentContentType) {
		this.attachmentContentType = attachmentContentType;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	@Autowired
	public void setExportExcelService(ExportExcelService exportExcelService) {
		this.exportExcelService = exportExcelService;
	}

	@Autowired
	public void setEmpService(EmployeeService empService) {
		this.empService = empService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	@SuppressWarnings("unchecked")
	public String findUpload() {

		try {
			EmployeeBean empBean = null;
			if (StringUtils.isNotEmpty(pageName)) {
				empBean = (EmployeeBean) session.get("empBean");
			}else{
				entity.setPageNo(1);
			}
			entity = empService.findUpload(entity, empBean);
			session.put("empBean", entity);
		} catch (Exception e) {
			return "login";
		}

		return "findUpload";
	}
	public String upload() {
		try {
			String id = request.getParameter("id");
			String result = empService.upload(id);
			if (result.equals("timeOut")) {
				messageSession(CommonParamter.CHECK_FLG, "连接超时");
			} else if (result.equals("success")) {
				messageSession(CommonParamter.CHECK_SUCCESS, "上传数据");
			} else if (result.equals(CommonParamter.CHECK_FAIL)) {
				messageSession(CommonParamter.CHECK_FAIL, "上传数据");
			}else{
				messageSession(CommonParamter.CHECK_FLG,result);
			}
		} catch (Exception e) {
			log.error("find leadership error!reason:" + e.getMessage());
			return "fail";
		}
		return "upload";
	}
	
}
